<?php
include 'readDB.php';
include 'checks.php';
$entidad=$_GET['object'];
$params = $_GET['params'];
$paramsObj = json_decode($params,true);


if (isset($entidades[$entidad])){ //CHEQUEA SI LA ENTIDAD EXISTE
	$checkFields=checkFields($entidades[$entidad],$paramsObj);
	if ($checkFields==""){
			$query=makeSaveQuery($entidades[$entidad],$paramsObj,$entidad);
			mysql_query($query) or mysql_errno($conn);
// 			echo $query;
			$lastId=mysql_insert_id();
			$msj= "Object Inserted";
			$ok=true;
	}else{
			$msj= "Field " . $checkFields . " not exists for object " .  $entidad;
			$ok=false;
	}
}else{
		$msj= "Object " . $entidad . "not exists";
		$ok=false;
}

$ret=array("ok" => $ok,"msj" => $msj, "id" => $lastId);
echo json_encode($ret);

function makeSaveQuery($entidad,$pars,$object){
	$pre="INSERT INTO " . $object	 . "(";
    $post=" (";
	$keys=array_keys($pars);	
	for ($x=0;$x<count($keys);$x++){
		$fieldName=$entidad[$keys[$x]]["name"];
		$fieldValue=$pars[$fieldName];		
		$dateB=(strstr($entidad[$keys[$x]]["type"], 'date')!=""); // SI ES DATE
		$stringB=(strstr($entidad[$keys[$x]]["type"], 'varchar')!=""); // SI ES VARCHAR
		if ($dateB || $stringB){ //TODO: FICHAR OTRO TIPO DE STRING/DATE/ETC
			$fieldValue= "'" . $fieldValue . "'";
		}
		
		$pre = $pre . $fieldName;
		$post=$post . $fieldValue;
		if ($x+1<count($keys)){
			$pre = $pre . ',';
			$post = $post . ',';
		}else{
			$pre = $pre . ') ';
			$post = $post . ') ';
		}
	}
	return $pre . "VALUES" . $post;
}

?>